<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SQL格式化工具</title>
    <link rel="icon" type="image/x-icon" href="/tools/static/favicon.ico">
    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 20px;
            background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
            color: #1f2937;
            position: relative;
        }
        h1 {
            color: #1e40af;
            text-align: center;
            margin-bottom: 40px;
            font-size: 2.5rem;
            font-weight: 700;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
        }
        .container {
            display: flex;
            gap: 30px;
            background: #ffffff;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
        }
        .input-area, .output-area {
            flex: 1;
            position: relative;
        }
        h3 {
            color: #374151;
            margin-bottom: 15px;
            font-size: 1.25rem;
            font-weight: 600;
        }
        .textarea-wrapper {
            position: relative;
            background: #f9fafb;
            border-radius: 12px;
            border: 1px solid #d1d5db;
            transition: border-color 0.3s ease;
        }
        .textarea-wrapper:hover {
            border-color: #93c5fd;
        }
        textarea {
            width: 100%;
            height: 500px;
            padding: 15px;
            font-family: 'Fira Code', 'Courier New', monospace;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.6;
            border: none;
            resize: vertical;
            box-sizing: border-box;
            background: transparent;
            color: #1f2937;
        }
        textarea:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
        }
        .output-container {
            position: relative;
            height: 500px;
            overflow-y: auto;
            font-family: 'Fira Code', 'Courier New', monospace;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.6;
            padding: 15px;
            background: #f9fafb;
            border-radius: 12px;
            border: 1px solid #d1d5db;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }
        .output-container:hover {
            border-color: #93c5fd;
        }
        .output-container.wrap {
            overflow-x: hidden;
        }
        .output-container.wrap .line-content {
            white-space: pre-wrap;
            word-break: break-all;
        }
        .output-container.no-wrap {
            overflow-x: auto;
        }
        .output-container.no-wrap .line-content {
            white-space: pre;
        }
        .line {
            display: flex;
            align-items: flex-start;
        }
        .line-number {
            width: 40px;
            color: #6b7280;
            text-align: right;
            padding-right: 10px;
            border-right: 1px solid #e5e7eb;
            user-select: none;
            flex-shrink: 0;
        }
        .line-content {
            flex: 1;
            padding-left: 15px;
            color: #1f2937;
        }
        .buttons {
            margin: 20px 0;
            display: flex;
            gap: 12px;
            justify-content: center;
        }
        button {
            padding: 12px 24px;
            cursor: pointer;
            background: linear-gradient(45deg, #3b82f6, #2563eb);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            transition: transform 0.2s, box-shadow 0.3s, background 0.3s;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
            background: linear-gradient(45deg, #60a5fa, #3b82f6);
        }
        .copy-btn {
            background: linear-gradient(45deg, #34d399, #10b981);
        }
        .copy-btn:hover {
            background: linear-gradient(45deg, #6ee7b7, #34d399);
        }
        .error {
            color: #dc2626;
            margin-top: 10px;
            padding: 10px;
            background: #fee2e2;
            border-radius: 8px;
            display: none;
            font-size: 14px;
        }
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #10b981;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            font-weight: 500;
            opacity: 0;
            transform: translateY(-20px);
            transition: opacity 0.3s ease, transform 0.3s ease;
            z-index: 1000;
        }
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        .toast .close-btn {
            cursor: pointer;
            font-size: 16px;
            line-height: 1;
            color: #d1fae5;
        }
        .toast .close-btn:hover {
            color: #ffffff;
        }
        .checkbox-wrapper {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .checkbox-wrapper label {
            font-size: 14px;
            color: #374151;
            cursor: pointer;
        }
        .checkbox-wrapper input[type="checkbox"] {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<h1>SQL格式化工具</h1>
<div class="container">
    <div class="input-area">
        <h3>输入SQL</h3>
        <div class="textarea-wrapper">
            <textarea id="inputSql" placeholder="在此输入SQL语句..."></textarea>
        </div>
        <div class="buttons">
            <button onclick="formatSql()">格式化</button>
            <button onclick="compressSql()">压缩</button>
            <button onclick="clearInput()">清空</button>
        </div>
        <div id="errorMsg" class="error"></div>
    </div>
    <div class="output-area">
        <h3>输出结果</h3>
        <div id="outputSql" class="output-container wrap"></div>
        <div class="buttons">
            <button class="copy-btn" onclick="copyOutput()">复制</button>
        </div>
    </div>
</div>

<!-- 引入 sql-formatter 库 -->
<script src="/tools/static/js/sql_formatter.js"></script>

<script>
    // 确保 sqlFormatter 可用
    if (typeof sqlFormatter === 'undefined') {
        console.error('sqlFormatter is not loaded. Please check if the script is correctly included.');
        alert('无法加载 SQL 格式化库，请检查网络连接或稍后重试。');
    }


    // 占位符处理：临时替换 MyBatis 占位符为简单的占位符（?）
    function preprocessSql(sql) {
        const placeholderMap = new Map();
        let counter = 1;
        const placeholderRegex = /#\{[^}]+\}/g;
        const placeholders = sql.match(placeholderRegex) || [];
        placeholders.forEach(placeholder => {
            const tempVar = `?${counter++}`; // 使用 ?1, ?2 形式的占位符
            placeholderMap.set(tempVar, placeholder);
            sql = sql.replace(placeholder, tempVar);
        });
        return { processedSql: sql, placeholderMap };
    }

    // 还原占位符
    function postprocessSql(sql, placeholderMap) {
        let result = sql;
        placeholderMap.forEach((original, tempVar) => {
            result = result.replace(tempVar, original);
        });
        return result;
    }

    async function formatSql() {
        const input = document.getElementById('inputSql').value;
        const output = document.getElementById('outputSql');
        const errorMsg = document.getElementById('errorMsg');

        if (!input.trim()) {
            errorMsg.textContent = '请输入SQL语句！';
            errorMsg.style.display = 'block';
            output.innerHTML = '';
            return;
        }

        try {
            let formattedSql;

            // 尝试前端格式化
            if (typeof sqlFormatter !== 'undefined') {
                // 预处理占位符
                const { processedSql, placeholderMap } = preprocessSql(input);

                // 使用 sql-formatter 格式化
                formattedSql = sqlFormatter.format(processedSql, {
                    language: 'mysql',
                    indent: '  ',
                    uppercase: true
                });

                // 还原占位符
                formattedSql = postprocessSql(formattedSql, placeholderMap);
            } else {
                throw new Error('SQL 格式化库未加载，将使用后端格式化。');
            }

            renderOutput(formattedSql);
            errorMsg.style.display = 'none';
        } catch (e) {
            // 如果前端格式化失败，回退到后端格式化
            try {
                const response = await fetch('/tools/sql/formatSql', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ sql: input, action: 'format' })
                });
                const result = await response.json();

                if (response.ok) {
                    renderOutput(result.data);
                    errorMsg.style.display = 'none';
                } else {
                    throw new Error(result.error || '后端格式化失败');
                }
            } catch (backendError) {
                errorMsg.textContent = '错误：' + (e.message || '格式化失败') + '（后端错误：' + backendError.message + '）';
                errorMsg.style.display = 'block';
                output.innerHTML = '';
            }
        }
    }

    async function compressSql() {
        const input = document.getElementById('inputSql').value;
        const output = document.getElementById('outputSql');
        const errorMsg = document.getElementById('errorMsg');

        if (!input.trim()) {
            errorMsg.textContent = '请输入SQL语句！';
            errorMsg.style.display = 'block';
            output.innerHTML = '';
            return;
        }

        try {
            const response = await fetch('/tools/sql/formatSql', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ sql: input, action: 'compress' })
            });
            const result = await response.json();

            if (response.ok) {
                renderOutput(result.data);
                errorMsg.style.display = 'none';
            } else {
                throw new Error(result.error || '压缩失败');
            }
        } catch (e) {
            errorMsg.textContent = '错误：' + e.message;
            errorMsg.style.display = 'block';
            output.innerHTML = '';
        }
    }

    function clearInput() {
        document.getElementById('inputSql').value = '';
        document.getElementById('outputSql').innerHTML = '';
        document.getElementById('errorMsg').style.display = 'none';
    }

    function copyOutput() {
        const output = document.getElementById('outputSql');
        const text = Array.from(output.querySelectorAll('.line-content'))
            .map(span => span.textContent)
            .join('\n');

        // 降级方案：使用 textarea 和 document.execCommand 复制文本
        const unsecuredCopyToClipboard = (text) => {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed'; // 避免影响页面布局
            textArea.style.opacity = '0'; // 隐藏 textarea
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showToast('已复制到剪贴板', 'success');
                } else {
                    showToast('复制失败，请手动复制', 'error');
                }
            } catch (err) {
                showToast('复制失败：' + err.message, 'error');
            }
            document.body.removeChild(textArea);
        };

        // 直接使用降级方案
        unsecuredCopyToClipboard(text);
    }

    function renderOutput(sql) {
        const output = document.getElementById('outputSql');
        output.innerHTML = '';
        const lines = sql.split('\n');
        lines.forEach((line, index) => {
            const lineElement = document.createElement('div');
            lineElement.className = 'line';
            lineElement.innerHTML = `
                <span class="line-number">${index + 1}</span>
                <span class="line-content">${line || ' '}</span>
            `;
            output.appendChild(lineElement);
        });
    }

    function showToast(message) {
        const existingToast = document.querySelector('.toast');
        if (existingToast) {
            existingToast.remove();
        }

        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.innerHTML = `
            <span>${message}</span>
            <span class="close-btn">×</span>
        `;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.classList.add('show');
        }, 10);

        const autoCloseTimeout = setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);

        toast.querySelector('.close-btn').addEventListener('click', () => {
            clearTimeout(autoCloseTimeout);
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        });
    }
</script>
</body>
</html>